package com.jiubanqingchen.plugin.easyexcel.convert;

import com.alibaba.excel.converters.Converter;
import com.alibaba.excel.converters.ConverterKeyBuild;
import com.alibaba.excel.converters.DefaultConverterLoader;

import java.lang.reflect.Field;
import java.util.Map;

/**
 * @author light_dust
 * @since 2020/12/25 15:56
 */
@SuppressWarnings({"unchecked","rawtypes"})
public class CustomConverterLoader {

    //存放写时用到的converter
    private static final String ALL_CONVERTER = "allConverter";
    //存放所有的converter
    private static final String WRITE_CONVERTER = "defaultWriteConverter";

    //这里初始化自定义一些东西
    public void init() throws IllegalAccessException {
        DefaultConverterLoader converters = new DefaultConverterLoader();
        Field[] fields = converters.getClass().getDeclaredFields();
        for (Field field : fields) {
            field.setAccessible(true);
            if (field.getType() == Map.class) {
                Map<String, Converter> oldMap = (Map<String, Converter>) field.get(converters);
                if (WRITE_CONVERTER.equalsIgnoreCase(field.getName())) {
                    putWriteConverter(oldMap, new LocalDateTimeConverter());
                    putWriteConverter(oldMap, new TimestampTimeConverter());
                    putWriteConverter(oldMap, new SqlDateStringConverter());
                } else if (ALL_CONVERTER.equalsIgnoreCase(field.getName())) {
                    putAllConverter(oldMap, new LocalDateTimeConverter());
                    putAllConverter(oldMap, new TimestampTimeConverter());
                    putAllConverter(oldMap, new SqlDateStringConverter());
                }
                field.set(converters, oldMap);
            }
        }
    }

    private void putWriteConverter(Map<String, Converter> map, Converter converter) {
        map.put(ConverterKeyBuild.buildKey(converter.supportJavaTypeKey()), converter);
    }

    private void putAllConverter(Map<String, Converter> map, Converter converter) {
        map.put(ConverterKeyBuild.buildKey(converter.supportJavaTypeKey(), converter.supportExcelTypeKey()), converter);
    }

}
